package com.im.app.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.im.app.mapper.DoyumingMapper;
import com.im.app.mapper.IPersonhostMapper;
import com.im.app.model.Doyuming;
import com.im.app.model.Personhost;
import com.im.app.model.User;
import com.im.app.service.IPersonhostService;
import com.im.app.utils.HttpUtils;
import com.im.app.utils.RandomNum;
import com.im.app.utils.ResponseResult;
import org.jim.core.packets.Group;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class IPersonhostImpl extends ServiceImpl<IPersonhostMapper, Personhost> implements IPersonhostService {

    @Resource
    private IPersonhostMapper iPersonhostMapper;
    @Resource
    private DoyumingMapper doyumingMapper;
    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
    @Override
    public Personhost getPersonhostByCode(String code) {
        QueryWrapper<Personhost> personhostQueryWrapper = new QueryWrapper<>();
        personhostQueryWrapper.eq("shortcode",code);
        return iPersonhostMapper.selectOne(personhostQueryWrapper);
    }

    @Override
    public Personhost getPersonHostByDomain(String domain){
        QueryWrapper<Personhost> personhostQueryWrapper = new QueryWrapper<>();
        personhostQueryWrapper.eq("url",domain);
        return iPersonhostMapper.selectOne(personhostQueryWrapper);
    }

    @Override
    public Personhost getPersonHostByKaMiCode(String code){
        QueryWrapper<Personhost> personhostQueryWrapper = new QueryWrapper<>();
        personhostQueryWrapper.eq("kami_code",code);
        return iPersonhostMapper.selectOne(personhostQueryWrapper);
    }


    /**
     * 客服分配域名
     *
     * @param user 用户管理
     * @return 结果
     */
    @Override
    public void updateUsersByOpration(User user) {
        Personhost rkPersonHost = iPersonhostMapper.getPersonhostByUserIdAndType(user.getUserId(),1);
        if(null == rkPersonHost){
            Doyuming rkym = doyumingMapper.selectDoyumingBYOne("1");//入口域名
            if (rkym == null) return;
            rkPersonHost = new Personhost();
            rkPersonHost.setLeixing(1);
            rkPersonHost.setShortcode(RandomNum.randomxiaoxie(4));
            rkPersonHost.setUrl("http://"+ RandomNum.randomxiaoxie(10)+"."+rkym.getDomain());
            rkPersonHost.setStatus(2);
            rkPersonHost.setUserId(user.getUserId());
            rkPersonHost.setDomain(rkym.getDomain());
            int rknum = iPersonhostMapper.insert(rkPersonHost);
            if(rknum>0){
                if(rkym.getFenpeicount()==0){
                    rkym.setAddTime(new Date());
                }
                rkym.setFenpeicount(rkym.getFenpeicount()+1);
                rkym.setIsUse(1);
                doyumingMapper.updateById(rkym);
            }
        }else{
            String url = rkPersonHost.getUrl();
            String str = getHost(url.replace("http://",""));
            Doyuming doyuming = doyumingMapper.selectDoyumingByDomain(str);
            if(null == doyuming){
                Doyuming newrk = doyumingMapper.selectDoyumingBYOne("1");//入口域名
                if (newrk == null) return;
                rkPersonHost.setDomain(newrk.getDomain());
                rkPersonHost.setUrl("http://"+ RandomNum.randomxiaoxie(10)+"."+newrk.getDomain());
                int i=iPersonhostMapper.updateById(rkPersonHost);
                if(i>0){
                    newrk.setFenpeicount(newrk.getFenpeicount()+1);
                    newrk.setIsUse(1);
                    doyumingMapper.updateById(newrk);
                }
            }
        }
    }

    /**
     * 群卡密分配域名
     * @param group
     * @return 结果
     */
    @Override
    public void updateGroupOpration(Group group) {
        Personhost rkPersonHost = iPersonhostMapper.getPersonhostByGroupIdAndType(group.getGroupId(),1);
        if(null == rkPersonHost){
            Doyuming rkym = doyumingMapper.selectDoyumingBYOne("1");//入口域名
            rkPersonHost=new Personhost();
            rkPersonHost.setLeixing(1);
            rkPersonHost.setShortcode(RandomNum.randomxiaoxie(4));
            rkPersonHost.setUrl("http://"+ RandomNum.randomxiaoxie(10)+"."+rkym.getDomain());
            rkPersonHost.setStatus(2);
            rkPersonHost.setUserId(group.getOwnerId());
            rkPersonHost.setGroupId(group.getGroupId());
            rkPersonHost.setDomain(rkym.getDomain());
            int rknum = iPersonhostMapper.insert(rkPersonHost);
            if(rknum>0){
                if(rkym.getFenpeicount()==0){
                    rkym.setAddTime(new Date());
                }
                rkym.setFenpeicount(rkym.getFenpeicount()+1);
                doyumingMapper.updateById(rkym);
            }
        }else{
            String url = rkPersonHost.getUrl();

            String str = getHost(url.replace("http://",""));
            log.info("updateGroupOpration {}",str);
            Doyuming doyuming = doyumingMapper.selectDoyumingByDomain(str);
            if(null == doyuming){
                Doyuming newrk = doyumingMapper.selectDoyumingBYOne("1");//入口域名
                rkPersonHost.setDomain(newrk.getDomain());
                rkPersonHost.setUrl("http://"+ RandomNum.randomxiaoxie(10)+"."+newrk.getDomain());
                int i=iPersonhostMapper.updateById(rkPersonHost);
                if(i>0){
                    newrk.setFenpeicount(newrk.getFenpeicount()+1);
                    doyumingMapper.updateById(newrk);
                }
            }
        }
    }

    /**
     * 独立卡密客服分配域名
     * @param user 用户管理
     * @return 结果
     */
    @Override
    public void updateUsersByDlOpration(User user,String code) {
        Doyuming doyuming = doyumingMapper.selectDlDoyumingBYOne("3");//独立域名
        if(null!=doyuming){
            Personhost singelPerson=new Personhost();
            singelPerson.setLeixing(3);
            singelPerson.setShortcode(RandomNum.randomxiaoxie(4));
            singelPerson.setUrl("http://"+doyuming.getDomain());
            singelPerson.setStatus(2);
            singelPerson.setUserId(user.getUserId());
            singelPerson.setDomain(doyuming.getDomain());
            singelPerson.setKamiCode(code);
            int result = iPersonhostMapper.insert(singelPerson);
            if(result>0){
                doyuming.setIsUse(1);
                doyumingMapper.updateById(doyuming);
            }
        }
    }

    /**
     * 分配备用落地域名
     * @param user 用户管理
     * @return 结果
     */
    @Override
    public void repairOpration(User user) {

    }

    private String getHost(String  serverName){
        int count = countOccurrences(serverName,"\\.");
        if (count == 1){
            return serverName;
        } else if (count == 2) {
            return serverName.substring(serverName.lastIndexOf(".",serverName.lastIndexOf(".")-1)+1);
        } else{
            int index = serverName.indexOf(".")+1;
            return  serverName.substring(index);
        }
    }

    public int countOccurrences(String str, String target) {
        Pattern pattern = Pattern.compile(target);
        Matcher matcher = pattern.matcher(str);
        int count = 0;
        while (matcher.find()) {
            count++;
        }
        return count;
    }

    /**
     * 更换入口域名
     * @param user 用户管理
     * @return 结果
     */
    @Override
    public ResponseResult<Personhost> backUpOpration(User user,Integer Id) {
        Personhost rkPersonHost = iPersonhostMapper.selectById(Id);
        ResponseResult<Personhost> result = new ResponseResult<>();
        if(rkPersonHost!=null){
            rkPersonHost.setUpdateTime(new Date());
            if(rkPersonHost.getLeixing()==1){
                String url = rkPersonHost.getUrl();
                int code = checkUrl2(url);
                String str = getHost(url.replace("http://",""));
                log.info("backUpOpration : {}",str);
                if (code == 110){ //屏蔽
                    Doyuming old = doyumingMapper.selectDoyumingByDomain(str);
                    if (old != null){
                        old.setStatus(3);
                        old.setFenpeicount(old.getFenpeicount() - 1);
                        doyumingMapper.updateById(old);
                    }
                    Doyuming doyuming = doyumingMapper.selectDoyumingByRandom("1");
                    if(null!=doyuming){
                        rkPersonHost.setUrl("http://"+ RandomNum.randomxiaoxie(10)+"."+doyuming.getDomain());
                        rkPersonHost.setLeixing(1);
                        rkPersonHost.setStatus(2);
                        rkPersonHost.setUserId(user.getUserId());
                        rkPersonHost.setDomain(doyuming.getDomain());
                        int rknum = iPersonhostMapper.updateById(rkPersonHost);
                        if(rknum>0){
                            doyuming.setFenpeicount(doyuming.getFenpeicount()+1);
                            doyuming.setIsUse(1);
                            doyumingMapper.updateById(doyuming);
                        }
                    }
                }else {
                    rkPersonHost.setUrl("http://"+RandomNum.randomxiaoxie(10)+"."+str);
                    iPersonhostMapper.updateById(rkPersonHost);
                }
            }else if(rkPersonHost.getLeixing()==3){
                rkPersonHost.setShortcode(RandomNum.randomxiaoxie(4));
                iPersonhostMapper.updateById(rkPersonHost);
            }
            result.setCode(200);
            result.setData(rkPersonHost);
        }
        return  result;
    }


    public final static String CHECKURL2 = "https://1251532263-9k3z4j5egl-gz.scf.tencentcs.com/?sign=bWV1d1BOcWp2U25WU3RqdUNhNjhwem50VWoweWRsY2F2eTdSWDRURHJDU01rTkhaMjYzcFF3&url=";
    private Integer checkUrl2(String url){
        String content = HttpUtils.sendGet(CHECKURL2 + url);
        JSONObject object=(JSONObject) JSONObject.parse(content);
        log.info("check {} = {}",url,content);
        return object.getInteger("status");
    }


    @Override
    public List<Personhost> getAll(String userId) {
        return iPersonhostMapper.getAll(userId);
    }



}
